package com.training.admin.web.controller.report;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.demo2do.core.entity.page.Page;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.utils.WebUtils;
import com.training.admin.entity.principal.Principal;
import com.training.admin.entity.project.ProjectTrainee;
import com.training.admin.entity.project.TrainingResult;
import com.training.admin.entity.search.ProjectTraineeReportSearch;
import com.training.admin.entity.security.Login;
import com.training.admin.service.PrincipalService;
import com.training.admin.service.ReportService;
import com.training.admin.service.TrainingCategoryService;
import com.training.admin.service.TrainingResultService;
import com.training.admin.web.controller.view.ExcelTemplateView;
/**
 * 
 * @author sjh
 *
 */
@Controller
@RequestMapping("")
@MenuSetting("menu-report")
public class ProjectTraineeFeirenController {
	
	//private static final Logger logger = LoggerFactory.getLogger(TrainerReportController.class);

	@Autowired
	private TrainingCategoryService trainingCategoryService;
	@Autowired
	private PrincipalService principalService;

	@Autowired
	private ReportService reportService;
	@Autowired
	private TrainingResultService trainingResultService;
	

	/**
	 * 项目学员表(非人)
	 * 
	 * @param page
	 * @return
	 */
	@SuppressWarnings("rawtypes")
    @RequestMapping(value = "/project-trainees-feiren", method = RequestMethod.GET)
	@MenuSetting("submenu-project-trainee-feiren")
	public ModelAndView projectTraineeFeirenReportSearch(Page page) {
		ModelAndView modelAndView = new ModelAndView("report/project-trainee-feiren-report-search");
		// 培训分类
		Map catMap = trainingCategoryService.getAllCategory();
		Map allCatMap = (Map) catMap.get("allCatMap");
		Map allNameIdMap = (Map) catMap.get("allNameIdMap");

		modelAndView.addObject("allCatMap", allCatMap);
		modelAndView.addObject("allNameIdMap", allNameIdMap);

		return modelAndView;
	}

	/**
	 * 项目学员表提交(非人)
	 * 
	 * @param page
	 * @return
	 */
	@SuppressWarnings("rawtypes")
    @RequestMapping(value = "/project-trainees-feiren", method = RequestMethod.GET, params = "filter")
	@MenuSetting("submenu-project-trainee-feiren")
	public ModelAndView onProjectTraineeFeirenReportSearch(ProjectTraineeReportSearch projectTraineeReportSearch,
			Page page, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("report/project-trainee-feiren-report");

		Login login = (Login) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Principal principal = principalService.loadByEmail(login.getEmail());
		if (principal.getAuthority().equals("ROLE_SUPER_USER")) {
			// 系统管理员
			// do nothing
		} else if (principal.getAuthority().equals("ROLE_DEPARTMENT_USER")) {
			// 事业部负责人
			projectTraineeReportSearch.setDepartmentId(principal.getDepartmentId());
		}

		int totals = reportService.count(projectTraineeReportSearch);
		if (totals > 0) {

			List projectTraineeList = reportService.search(projectTraineeReportSearch, page.with(totals));
			List<ProjectTrainee> projectTrainees = new ArrayList<ProjectTrainee>();
			for (int i = 0; i < projectTraineeList.size(); i++) {
				ProjectTrainee projectTrainee = (ProjectTrainee) projectTraineeList.get(i);
				// Course course= projectPhaseCourse.getCourse();
				// set survey result / suggestion to each course
				List<TrainingResult> trainingResultList = trainingResultService.listByTraineeAndProject(
						projectTrainee.getTrainee().getId(), projectTrainee.getProject().getId());
				int totalScore = 0;
				Float totalAbsence = (float) 0;
				int j = 0;
				String comment = "";
				boolean resit = false;
				for (; j < trainingResultList.size(); j++) {
					TrainingResult trainingResult = trainingResultList.get(j);
					if (trainingResult.getScore() > 0) {
						totalScore += trainingResult.getScore();
					}
					if (trainingResult.getAbsence() > 0) {
						totalAbsence += trainingResult.getAbsence();
					}
					if (trainingResult.isResit()) {
						resit = true;
					}
					if (!StringUtil.isBlank(trainingResult.getComment())) {
						comment += "    " + trainingResult.getComment();
					}

				}
				if (j > 0) {
					projectTrainee.setScore(Float.valueOf(totalScore / j));
					projectTrainee.setAbsence(totalAbsence);
				}
				projectTrainee.setResit(resit);
				projectTrainee.setComment(comment);
				projectTrainees.add(projectTrainee);
			}

			modelAndView.addObject("projectTrainees", projectTrainees);
			modelAndView.addObject("recordCount", projectTrainees.size());
			modelAndView.addObject("page", page);

		}

		modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));

		return modelAndView;
	}
	
	/**
	 * 项目学员表 - 导出
	 * 
	 * @param search
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/reports/project-trainee-feiren-report-export", method = RequestMethod.GET)
	@MenuSetting("submenu-project-trainee-feiren")
	public ModelAndView projectTraineeFeirenReportExport(ProjectTraineeReportSearch projectTraineeReportSearch,
			Page page) {

		ModelAndView modelAndView = new ModelAndView(
				new ExcelTemplateView("project-trainee-feiren-result.xls", "project-trainee-feiren-report.xls"));
		Login login = (Login) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Principal principal = principalService.loadByEmail(login.getEmail());
		if (principal.getAuthority().equals("ROLE_SUPER_USER")) {
			// 系统管理员
			// do nothing
		} else if (principal.getAuthority().equals("ROLE_DEPARTMENT_USER")) {
			// 事业部负责人
			projectTraineeReportSearch.setDepartmentId(principal.getDepartmentId());
		}

		int totals = reportService.count(projectTraineeReportSearch);
		if (totals > 0) {

			List projectTraineeList = reportService.searchForExport(projectTraineeReportSearch);
			List<Object[]> projectTrainees = new ArrayList<Object[]>();
			for (int i = 0; i < projectTraineeList.size(); i++) {
				ProjectTrainee projectTrainee = (ProjectTrainee) projectTraineeList.get(i);
				// Course course= projectPhaseCourse.getCourse();
				// set survey result / suggestion to each course
				List<TrainingResult> trainingResultList = trainingResultService.listByTraineeAndProject(
						projectTrainee.getTrainee().getId(), projectTrainee.getProject().getId());
				int totalScore = 0;
				Float totalAbsence = (float) 0;
				int j = 0;
				String comment = "";
				boolean resit = false;
				for (; j < trainingResultList.size(); j++) {
					TrainingResult trainingResult = trainingResultList.get(j);
					if (trainingResult.getScore() > 0) {
						totalScore += trainingResult.getScore();
					}
					if (trainingResult.getAbsence() > 0) {
						totalAbsence += trainingResult.getAbsence();
					}
					if (trainingResult.isResit()) {
						resit = true;
					}
					if (!StringUtil.isBlank(trainingResult.getComment())) {
						comment += "    " + trainingResult.getComment();
					}

				}
				if (j > 0) {
					projectTrainee.setScore(Float.valueOf(totalScore / j));
					projectTrainee.setAbsence(totalAbsence);
				}
				projectTrainee.setResit(resit);
				projectTrainee.setComment(comment);

				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

				projectTrainees.add(new Object[] { projectTrainee.getProject().getCode(),
						projectTrainee.getProject().getFirstCategory().getName() + "-"
								+ projectTrainee.getProject().getSecondCategory().getName(),
						projectTrainee.getProject().getName(), projectTrainee.getTrainee().getName(),
						projectTrainee.getTrainee().getCode(), projectTrainee.getTrainee().getEmail(),
						dateFormat.format(projectTrainee.getProject().getBeginDate()),
						dateFormat.format(projectTrainee.getProject().getEndDate()),
						((projectTrainee.getComplete() == null || projectTrainee.getComplete() == false) ? "否" : "是"), (projectTrainee.getResit() == null || projectTrainee.getResit() == false ? "否" : "是"),
						projectTrainee.getScore(), projectTrainee.getAbsence(), projectTrainee.getComment(),
						projectTrainee.getSpotScore(), projectTrainee.getInterviewTimes(), projectTrainee.getInterview(),
						projectTrainee.getCounselorTimes(), projectTrainee.getCounselor(), projectTrainee.getSeed()
				});
			}

			modelAndView.addObject("results", projectTrainees);

		}

		return modelAndView;

	}

}
